﻿using Company.Plc;
using Company.Shell.Interfaces;

namespace Company.Shell.Services
{
    class CollectManager : ICollectManager
    {
        private CancellationTokenSource cts = new CancellationTokenSource();
        public IRoomManager RoomManager { get; }
        public IPlc Plc { get; }
        public CollectManager(
            IPlc plc,
            IRoomManager roomManager)
        {
            Plc = plc;
            RoomManager = roomManager;
        }

        public void Start()
        {
            cts = new CancellationTokenSource();
            Task.Run(() =>
            {
                while (!cts.IsCancellationRequested)
                {
                    foreach (var room in RoomManager.Rooms)
                    {
                        if (cts.IsCancellationRequested)
                            break;
                        var array = Plc.Read(room.Address.ToString(), 100);
                        room.Resolve(array);
                        Thread.Sleep(100);
                    }
                }
            });
        }

        public void Stop() => cts.Cancel();
    }
}
